#include "webapi_http_utils.h"

#include <HTTPClient.h>
#include <HardwareSerial.h>
#include <WiFiClient.h>

namespace webapi {

bool HttpGet(const char* requestURL, String& responseContent) {
  HTTPClient httpClient;
  WiFiClient wifiClient;

  if (!httpClient.begin(wifiClient, requestURL)) {
    Serial.printf("Connect to %s FAILED!\r\n", requestURL);
    httpClient.end();
    return false;
  }

  int ret = httpClient.GET();
  if (ret < 0) {
    Serial.printf("Send request to %s FAILED!\r\n", requestURL);
    httpClient.end();
    return false;
  }

  responseContent.clear();
  char buffer[128] = "";
  int nbytes = 0;
  while ((nbytes = wifiClient.read((uint8_t*)buffer, sizeof(buffer))) > 0) {
    responseContent.concat(buffer, nbytes);
  }

  bool retval = true;
  if (nbytes < 0) {
    Serial.printf("Recv response from %s FAILED!\r\n", requestURL);
    retval = false;
  }

  httpClient.end();
  return retval;
}

}  // namespace webapi